package com.example.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.PutObjectResult;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class AliyunOssUtils_3 {

    public static String endpoint = "oss-cn-shenzhen.aliyuncs.com";
    public static String accessKeyId = "your accessKeyId";
    public static String accessKeySecret = "your accessKeySecret";

    // 创建阿里云登录凭证
    public static CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);

    // 创建OSSClient实例。
    public static OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

    /**
     * 创建bucket
     */
    public static void createBucket() {
        String bucketName = "java-hello-world";
        try {
            // 创建存储空间。
            ossClient.createBucket(bucketName);
        } catch (Exception e) {
            System.out.println("Error Message:" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 上传文件
     */
    public static void uploadFile() {
        // 填写Bucket名称，如果Bucket不存在， 可以先创建一个
        String bucketName = "java-hello-world";
        // 填写Object完整路径，需要包含文件名，但不用包含Bucket名称
        String objectName = "test/test.txt";

        try {
            String content = "Hello OSS";
            // 采用字节数组方式上传
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
            System.out.println("putObjectResult = " + putObjectResult.toString());
        } catch (Exception e) {
            System.out.println("Error Message:" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }

    /**
     * 下载文件
     */
    public static void downloadFile() {
        // 填写Bucket名称
        String bucketName = "java-hello-world";
        // 填写Object完整路径，需要包含文件名，但不用包含Bucket名称
        String objectName = "test/test.txt";

        try {
            // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);

            // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
            InputStream content = ossObject.getObjectContent();

            if (content != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                while (true) {
                    String line = reader.readLine();
                    if (line == null) {
                        break;
                    }
                    System.out.println("\n" + line);
                }
                // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
                content.close();
            }
        } catch (Exception e) {
            System.out.println("Error Message:" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 查询某个bucket的Object列表
     */
    public static void getObjectList() {
        // 填写Bucket名称
        String bucketName = "java-hello-world";

        try {
            // ossClient.listObjects返回ObjectListing实例，包含此次listObject请求的返回结果。
            ObjectListing objectListing = ossClient.listObjects(bucketName);

            int size = objectListing.getObjectSummaries().size();
            System.out.println("=========查询到的对象数量是：" + size);

            // objectListing.getObjectSummaries获取所有文件的描述信息。
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(" ======================== " + objectSummary.getKey() + "  " +
                        "(size = " + objectSummary.getSize() + ")");
            }
        } catch (Exception e) {
            System.out.println("Error Message:" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }

    /**
     * 删除某个对象
     */
    public static void deleteObject() {
        // 填写Bucket名称
        String bucketName = "java-hello-world";
        // 填写Object完整路径，需要包含文件名，但不用包含Bucket名称
        String objectName = "test/test.txt";
        try {
            // 删除文件
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException e) {
            System.out.println("Error Message:" + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public static void main(String[] args) throws Exception {
//        uploadFile();
//        downloadFile();
//        getObjectList();
//        deleteObject();
    }

}